﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using System.Security.Cryptography;

namespace Lg.Core.Encryption
{
    /// <summary>
    /// 请使用using()方式实例化对像，否则请在对像使用完毕后，执行 Dispose()方法回收资源
    /// </summary>
    public class RSAHelper:IDisposable
    {
        readonly RSA rsa=RSA.Create();
        readonly RSAEncryptionPadding padding = RSAEncryptionPadding.Pkcs1;
        public string? publicKey { get; }
        public string? privateKey { get; }
        public RSAHelper()
        {
            this.publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
            this.privateKey =Convert.ToBase64String(rsa.ExportRSAPrivateKey());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="publicKey">base64</param>
        /// <param name="privateKey">base64</param>
        public RSAHelper(string? publicKey,string? privateKey)
        {
            if (!string.IsNullOrEmpty(publicKey))
            {
                this.publicKey = publicKey;
                rsa.ImportSubjectPublicKeyInfo(new ReadOnlySpan<byte>(Convert.FromBase64String(publicKey)), out int bytesRead);
            }
            if (!string.IsNullOrEmpty(privateKey))
            {
                this.publicKey = privateKey;
                rsa.ImportRSAPrivateKey(new ReadOnlySpan<byte>(Convert.FromBase64String(privateKey)), out int bytesRead);
            }
        }
        public string Encrypt(string str)
        {
           byte[] bytes= rsa.Encrypt(Encoding.UTF8.GetBytes(str),padding);  
           return Convert.ToBase64String(bytes);
        }
        public string Dencrypt(string str)
        {
            byte[] bytes= rsa.Decrypt(Convert.FromBase64String(str),padding);
            return Encoding.UTF8.GetString(bytes);
        }

        public void Dispose()
        {
            rsa.Clear();
            rsa.Dispose();
        }
    }
}
